%% 1. 加载数据
candidate_data = readtable('附件1 数据-C题.xlsx', 'VariableNamingRule', 'preserve');
job_data = readtable('job_data.xlsx', 'VariableNamingRule', 'preserve'); % 招聘岗位数据
cpi_data = readtable('CPI.xlsx', 'VariableNamingRule', 'preserve');

% 重命名 CPI 和年份字段
cpi_data.Properties.VariableNames{'居民消费价格指数'} = 'CPI';
cpi_data.Properties.VariableNames{'年份'} = 'Year';

%% 2. 预处理：合并 CPI，补充宏观变量
candidate_data.Year = 2023 * ones(height(candidate_data), 1);
job_data.Year = 2023 * ones(height(job_data), 1);

candidate_data = join(candidate_data, cpi_data, 'Keys', 'Year', 'RightVariables', 'CPI');
job_data = join(job_data, cpi_data, 'Keys', 'Year', 'RightVariables', 'CPI');

% 补充 CPI 缺失值
candidate_data.CPI(isnan(candidate_data.CPI)) = mean(candidate_data.CPI, 'omitnan');
job_data.CPI(isnan(job_data.CPI)) = mean(job_data.CPI, 'omitnan');

% 添加宏观经济变量
macro_vars = {'yichang_gdp', 'national_unemployment', 'job_vacancy_rate', 'policy_support'};
macro_vals = [146771, 5.2, 3.5, 80];
for i = 1:length(macro_vars)
    candidate_data.(macro_vars{i}) = macro_vals(i) * ones(height(candidate_data), 1);
    job_data.(macro_vars{i}) = macro_vals(i) * ones(height(job_data), 1);
end

%% 3. 特征处理
% 将学历转为数值（如果尚未处理）
if iscell(candidate_data.edu_level)
    candidate_data.edu_level = double(categorical(candidate_data.edu_level));
end
if iscell(job_data.edu_required)
    job_data.edu_required = double(categorical(job_data.edu_required));
end

% 确保存在 ID 字段
if ~ismember('ID', candidate_data.Properties.VariableNames)
    candidate_data.ID = (1:height(candidate_data))';
end
if ~ismember('JobID', job_data.Properties.VariableNames)
    job_data.JobID = (1:height(job_data))';
end

%% 4. 人岗匹配逻辑（失业者推荐）
unemployed = candidate_data(candidate_data.预测 == 0, :); % 仅推荐失业者
recommendations = table();

for i = 1:height(unemployed)
    seeker = unemployed(i, :);
    scores = zeros(height(job_data), 1);

    for j = 1:height(job_data)
        job = job_data(j, :);

        % 匹配评分逻辑（简单线性相似度）
        score = 0;
        score = score + (1 - abs(seeker.age - job.age_required)/50); % 年龄匹配
        score = score + (1 - abs(seeker.edu_level - job.edu_required)/5); % 学历匹配
        score = score + (1 - abs(seeker.CPI - job.CPI)/100); % CPI 匹配
        score = score + (1 - abs(seeker.policy_support - job.policy_support)/100); % 政策支持匹配

        % 可加入更多特征，例如技能匹配、行业匹配等

        scores(j) = score;
    end

    % 推荐得分前 3 的岗位
    [~, top_idx] = maxk(scores, 3);
    top_jobs = job_data(top_idx, :);
    top_jobs.PersonID = repmat(seeker.ID, 3, 1);
    top_jobs.MatchScore = scores(top_idx);

    recommendations = [recommendations; top_jobs];
end

%% 5. 保存推荐结果
writetable(recommendations, 'job_recommendations.xlsx');